import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:hinge/common/index.dart";
import "package:mobx/mobx.dart";

part "detail_store.g.dart";

class DetailStore = _DetailStore with _$DetailStore;

abstract class _DetailStore with Store {
  @observable
  bool isLoading = false;

  @observable
  PerfumeModel? currentPerfume;

  @observable
  bool isLiked = false;

  @observable
  bool isCollected = false;

  @action
  Future<void> loadPerfumeDetail(String perfumeId) async {
    isLoading = true;
    EasyLoading.show(status: 'Loading...');
    await Future.delayed(const Duration(milliseconds: 300));

    try {
      // 获取香水详情
      currentPerfume = PerfumeService.getPerfumeById(perfumeId);

      // 获取点赞和收藏状态
      final currentUser = UserService.getCurrentUser();
      if (currentUser != null && currentPerfume != null) {
        isLiked = LikeCollectionService.isPerfumeLiked(
          currentUser.id,
          currentPerfume!.id,
        );
        isCollected = LikeCollectionService.isPerfumeCollected(
          currentUser.id,
          currentPerfume!.id,
        );
      }

      EasyLoading.dismiss();
    } catch (e) {
      print("加载香水详情失败: $e");
      currentPerfume = null;
      EasyLoading.showError('Failed to load');
    } finally {
      isLoading = false;
    }
  }

  @action
  void reset() {
    currentPerfume = null;
    isLiked = false;
    isCollected = false;
  }

  @action
  Future<void> deletePerfume(String perfumeId) async {
    try {
      EasyLoading.show(status: 'Deleting...');
      int id = int.parse(perfumeId);
      await PerfumeService.deletePerfume(id);
      reset();
      await Future.delayed(const Duration(milliseconds: 300));
      EasyLoading.showSuccess('Successfully deleted');
    } catch (e) {
      print("删除香水失败: $e");
      EasyLoading.showError('Failed to delete: ${e.toString()}');
    }
  }

  @action
  Future<bool> likePerfume() async {
    if (currentPerfume == null) return false;

    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      return false;
    }

    final result = await LikeCollectionService.likePerfume(
      currentUser.id,
      currentPerfume!.id,
    );

    if (result) {
      isLiked = LikeCollectionService.isPerfumeLiked(
        currentUser.id,
        currentPerfume!.id,
      );
    }

    return result;
  }

  @action
  Future<bool> collectPerfume() async {
    if (currentPerfume == null) return false;

    final currentUser = UserService.getCurrentUser();
    if (currentUser == null || UserService.isGuestUser()) {
      return false;
    }

    final result = await LikeCollectionService.collectPerfume(
      currentUser.id,
      currentPerfume!.id,
    );

    if (result) {
      isCollected = LikeCollectionService.isPerfumeCollected(
        currentUser.id,
        currentPerfume!.id,
      );
    }

    return result;
  }
}
